import db from '../config/database.js'
import {
  generateOrderNo,
  generateVerificationCode,
  isValidPhone,
  isValidIdCard
} from '../utils/helpers.js'

// 创建订单
export async function createOrder(req, res) {
  const connection = await db.getConnection()

  try {
    const {exhibition_id, buyer_name, buyer_phone, buyer_id_card, items, tickets} = req.body

    // 验证必填字段
    if (!exhibition_id || !buyer_name || !buyer_phone || !buyer_id_card || !items || items.length === 0) {
      return res.status(400).json({
        success: false,
        error: '缺少必填字段'
      })
    }

    // 验证票据信息
    if (!tickets || tickets.length === 0) {
      return res.status(400).json({
        success: false,
        error: '请填写每张票的游客信息'
      })
    }

    // 计算总票数
    const totalTickets = items.reduce((sum, item) => sum + item.quantity, 0)
    if (tickets.length !== totalTickets) {
      return res.status(400).json({
        success: false,
        error: `票数不匹配：需要${totalTickets}张票的信息，实际提供${tickets.length}张`
      })
    }

    // 验证每张票的信息
    for (const ticket of tickets) {
      if (!ticket.visitor_name || !ticket.visitor_phone || !ticket.visitor_id_card) {
        return res.status(400).json({
          success: false,
          error: '每张票都需要填写完整的游客信息'
        })
      }

      if (!isValidPhone(ticket.visitor_phone)) {
        return res.status(400).json({
          success: false,
          error: `手机号 ${ticket.visitor_phone} 格式不正确`
        })
      }

      if (!isValidIdCard(ticket.visitor_id_card)) {
        return res.status(400).json({
          success: false,
          error: `身份证号 ${ticket.visitor_id_card} 格式不正确`
        })
      }
    }

    // 验证购票人手机号
    if (!isValidPhone(buyer_phone)) {
      return res.status(400).json({
        success: false,
        error: '购票人手机号格式不正确'
      })
    }

    // 验证购票人身份证号
    if (!isValidIdCard(buyer_id_card)) {
      return res.status(400).json({
        success: false,
        error: '购票人身份证号格式不正确'
      })
    }

    // 开始事务
    await connection.beginTransaction()

    // 生成订单号和验票码
    const orderNo = generateOrderNo()
    const verificationCode = generateVerificationCode()

    // 计算总价并检查库存
    let totalAmount = 0
    for (const item of items) {
      const [ticketTypes] = await connection.query(
        'SELECT price, stock FROM ticket_types WHERE id = ?',
        [item.ticket_type_id]
      )

      if (ticketTypes.length === 0) {
        await connection.rollback()
        return res.status(400).json({
          success: false,
          error: `票种 ${item.ticket_type_id} 不存在`
        })
      }

      const ticketType = ticketTypes[0]
      
      // 检查库存（stock = -1 表示无限库存）
      if (ticketType.stock !== -1) {
        // 查询该票种已售数量
        const [soldResult] = await connection.query(
          `SELECT COALESCE(SUM(oi.quantity), 0) as sold 
           FROM order_items oi 
           JOIN orders o ON oi.order_id = o.id 
           WHERE oi.ticket_type_id = ? AND o.status IN ('pending', 'paid')`,
          [item.ticket_type_id]
        )
        
        const sold = soldResult[0].sold
        const available = ticketType.stock - sold
        
        if (available < item.quantity) {
          await connection.rollback()
          return res.status(400).json({
            success: false,
            error: `票种库存不足，剩余 ${available} 张`
          })
        }
      }

      totalAmount += ticketType.price * item.quantity
    }

    // 插入订单
    const [orderResult] = await connection.query(
      `INSERT INTO orders 
       (order_no, exhibition_id, buyer_name, buyer_phone, buyer_id_card, 
        total_amount, status, verification_code, created_at) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())`,
      [
        orderNo,
        exhibition_id,
        buyer_name,
        buyer_phone,
        buyer_id_card,
        totalAmount,
        'pending',
        verificationCode
      ]
    )

    const orderId = orderResult.insertId

    // 插入订单项和票据
    let ticketIndex = 0
    for (const item of items) {
      const [ticketTypes] = await connection.query(
        'SELECT name, price FROM ticket_types WHERE id = ?',
        [item.ticket_type_id]
      )

      // 插入订单项
      const [orderItemResult] = await connection.query(
        `INSERT INTO order_items 
         (order_id, ticket_type_id, ticket_type_name, quantity, price, subtotal) 
         VALUES (?, ?, ?, ?, ?, ?)`,
        [
          orderId,
          item.ticket_type_id,
          ticketTypes[0].name,
          item.quantity,
          ticketTypes[0].price,
          ticketTypes[0].price * item.quantity
        ]
      )

      const orderItemId = orderItemResult.insertId

      // 为该订单项的每张票插入票据记录
      for (let i = 0; i < item.quantity; i++) {
        const ticketInfo = tickets[ticketIndex]
        const ticketVerificationCode = generateVerificationCode()

        await connection.query(
          `INSERT INTO tickets 
           (order_id, order_item_id, ticket_type_name, visitor_name, visitor_phone, 
            visitor_id_card, verification_code, created_at) 
           VALUES (?, ?, ?, ?, ?, ?, ?, NOW())`,
          [
            orderId,
            orderItemId,
            ticketTypes[0].name,
            ticketInfo.visitor_name,
            ticketInfo.visitor_phone,
            ticketInfo.visitor_id_card,
            ticketVerificationCode
          ]
        )

        ticketIndex++
      }
    }

    // 提交事务
    await connection.commit()

    res.status(201).json({
      success: true,
      data: {
        order_no: orderNo,
        order_id: orderId,
        total_amount: totalAmount,
        verification_code: verificationCode
      }
    })
  } catch (error) {
    await connection.rollback()
    console.error('创建订单错误:', error)
    res.status(500).json({
      success: false,
      error: '创建订单失败'
    })
  } finally {
    connection.release()
  }
}

// 获取订单详情
export async function getOrder(req, res) {
  try {
    const {orderNo} = req.params

    // 查询订单
    const [orders] = await db.query(
      `SELECT o.*, e.title as exhibition_title, e.location as exhibition_location,
              e.start_date, e.end_date
       FROM orders o
       LEFT JOIN exhibitions e ON o.exhibition_id = e.id
       WHERE o.order_no = ?`,
      [orderNo]
    )

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      })
    }

    const order = orders[0]

    // 查询订单项
    const [items] = await db.query(
      'SELECT * FROM order_items WHERE order_id = ?',
      [order.id]
    )

    // 查询票据信息
    const [tickets] = await db.query(
      'SELECT * FROM tickets WHERE order_id = ? ORDER BY id ASC',
      [order.id]
    )

    res.json({
      success: true,
      data: {
        ...order,
        items,
        tickets
      }
    })
  } catch (error) {
    console.error('获取订单详情错误:', error)
    res.status(500).json({
      success: false,
      error: '获取订单详情失败'
    })
  }
}

// 根据手机号查询订单
export async function getOrdersByPhone(req, res) {
  try {
    const {phone} = req.params

    // 查询订单
    const [orders] = await db.query(
      `SELECT o.*, e.title as exhibition_title, e.location as exhibition_location,
              e.start_date, e.end_date
       FROM orders o
       LEFT JOIN exhibitions e ON o.exhibition_id = e.id
       WHERE o.buyer_phone = ?
       ORDER BY o.created_at DESC`,
      [phone]
    )

    // 为每个订单查询订单项
    for (const order of orders) {
      const [items] = await db.query(
        'SELECT * FROM order_items WHERE order_id = ?',
        [order.id]
      )
      order.items = items
    }

    res.json({
      success: true,
      data: orders
    })
  } catch (error) {
    console.error('根据手机号查询订单错误:', error)
    res.status(500).json({
      success: false,
      error: '查询订单失败'
    })
  }
}

// 获取当前用户的订单（需要认证）
export async function getMyOrders(req, res) {
  try {
    // 从 JWT token 中获取用户信息
    const userId = req.user.id

    // 查询用户信息获取手机号
    const [users] = await db.query('SELECT phone FROM users WHERE id = ?', [userId])

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        error: '用户不存在'
      })
    }

    const userPhone = users[0].phone

    // 查询该用户的订单
    const [orders] = await db.query(
      `SELECT o.*, e.title as exhibition_title, e.location as exhibition_location,
              e.start_date, e.end_date
       FROM orders o
       LEFT JOIN exhibitions e ON o.exhibition_id = e.id
       WHERE o.buyer_phone = ?
       ORDER BY o.created_at DESC`,
      [userPhone]
    )

    // 为每个订单查询订单项
    for (const order of orders) {
      const [items] = await db.query(
        'SELECT * FROM order_items WHERE order_id = ?',
        [order.id]
      )
      order.items = items
    }

    res.json({
      success: true,
      data: orders
    })
  } catch (error) {
    console.error('获取用户订单错误:', error)
    res.status(500).json({
      success: false,
      error: '查询订单失败'
    })
  }
}

// 更新订单状态
export async function updateOrderStatus(req, res) {
  try {
    const {orderNo} = req.params
    const {status} = req.body

    // 验证状态
    const validStatuses = ['pending', 'paid', 'cancelled']
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        error: '无效的订单状态'
      })
    }

    // 更新订单状态
    const [result] = await db.query(
      'UPDATE orders SET status = ?, updated_at = NOW() WHERE order_no = ?',
      [status, orderNo]
    )

    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      })
    }

    res.json({
      success: true,
      data: {
        order_no: orderNo,
        status
      }
    })
  } catch (error) {
    console.error('更新订单状态错误:', error)
    res.status(500).json({
      success: false,
      error: '更新订单状态失败'
    })
  }
}
